package com.wx.lambda.ii.chapter11;

import cn.hutool.core.thread.ThreadUtil;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.function.Supplier;

@Data
@AllArgsConstructor
public class Shop {
    private String name;


    public String getPriceOld(String product) {
        double price = calculatePrice(product);
        Discount.Code code = Discount.Code.values()[
                new Random().nextInt(Discount.Code.values().length)];
        return String.format("%s:%.2f:%s", name, price, code);
    }

    /**
     * 获取价格
     *
     * @param product 产品
     * @return double
     */
    public Future<Double> getPrice(String product) {
        CompletableFuture<Double> future = new CompletableFuture<>();
        new Thread(() -> {
            try {
                double v = calculatePrice(product);

                future.complete(v);
            } catch (Exception e) {
                future.completeExceptionally(e);

            }
        }).start();
        return future;
    }



    public Future<Double> getPriceAsync(String product) {
        return CompletableFuture.supplyAsync(()->calculatePrice(product));
    }

    /**
     * 计算价格
     *
     * @param product 产品
     * @return double 价格
     */
    private double calculatePrice(String product) {
        ThreadUtil.safeSleep(3000);
        return Math.random() * product.charAt(0) + product.charAt(1);
    }
}